import logging
import datetime

from appengine_django.models import BaseModel
from google.appengine.ext import db
from player.models import Player
from stadium.models import Stadium
        
class Match(BaseModel):    
    owner = db.ReferenceProperty(Player,collection_name='my_matches',verbose_name="Creador")    
    stadium = db.ReferenceProperty(Stadium,collection_name='matches',verbose_name="Estadio")
    datetime = db.DateTimeProperty(verbose_name="Fecha y Hora")
    name = db.StringProperty(verbose_name="Nombre del partido")
        
    def __unicode__(self):
        return "%s %s"%(self.name,datetime.datetime.strftime(self.datetime,"%d/%m/%Y %H:%M"))
    
    @classmethod
    def create(cls,matchDict,owner):
        logging.info(matchDict)
        dt = datetime.datetime.strptime("%s %s"%(matchDict.get('date'),matchDict.get('hora')),"%Y-%m-%d %H:%M")
        new_match = Match(owner=owner,datetime=dt,name=matchDict.get('name')).put()
        
        for player_email in matchDict.getlist('friend'):
            c_player = Player.all().filter('email =',player_email).get()
            if not c_player:
                c_player = Player(email=player_email).put()                      
            MatchPlayer(match=new_match,player=c_player).put()            
        return new_match
    
    def get_confirmations(self):
        return list(self.match_players.filter('confirm =',True))
    
class MatchPlayer(BaseModel):
    match = db.ReferenceProperty(Match,collection_name='match_players')
    player = db.ReferenceProperty(Player,collection_name="matches")
    confirm = db.BooleanProperty(default=False)
    confirm_date = db.DateTimeProperty()
    goals = db.IntegerProperty(default=0)